package com.qunar.dyds.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.HtmlUtils;

import com.qunar.base.meerkat.util.StringUtil;
import com.qunar.common.admin.constant.WebConstants;
import com.qunar.dyds.dto.ListObject;
import com.qunar.dyds.entity.InviteCode;
import com.qunar.dyds.entity.InviteCodeStatus;
import com.qunar.dyds.util.ValidateUtil;

/**
 * 报名序号操作
 */
@Controller("invitecode")
public class InviteCodeController extends AbstractController {

    @RequestMapping(value = "list")
    public ModelAndView listAction(@RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "certNo", required = false) String certNo,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "startIndex", required = false, defaultValue = "0") int startIndex,
            @RequestParam(value = "row", required = false, defaultValue = WebConstants.DEFAULT_PAGE_SIZE_STR) int row) {

        Map<String, Object> cond = new HashMap<String, Object>();
        cond.put("code", code);
        cond.put("certNo", certNo);
        cond.put("status", status);
        cond.put("sort", "status, id");

        // 查询总记录数
        int totalCount = inviteCodeService.getCount(cond);

        // 查询记录列表
        List<InviteCode> beans = inviteCodeService.search(cond, startIndex, row);

        // 绑定结果列表
        ListObject lstObj = new ListObject(startIndex, row, totalCount, beans);
        ModelAndView view = new ModelAndView("invitecode/list");
        view.addObject("lstObj", lstObj);
        view.addObject("cond", cond);

        return view;
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add() {
        return "invitecode/add";
    }

    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Map<Object, Object> addSubmit(@RequestParam("codelist") String codelist) {

        codelist = HtmlUtils.htmlEscape(codelist);

        String codes[] = codelist.split("\n");

        List<InviteCode> codeBeans = new LinkedList<InviteCode>();

        // 参数检查
        for (int i = 0; i < codes.length; i++) {
            String s[] = codes[i].split(",");
            if (s.length < 2 || s[0] == null || s[1] == null) {
                return errorJson("缺少报名序号或身份证号" + codes[i]);
            }

            String _code = s[0].trim();
            String _certNo = s[1].trim();
            if (!PATTERN_CODE.matcher(_code).matches()) {
                return errorJson("无效的报名序号" + _code);
            }
            String error = ValidateUtil.isValidCart(_certNo);
            if (error != null) {
                return errorJson("无效的身份证号" + _certNo);
            }

            InviteCode code = new InviteCode();
            code.setCode(_code);
            code.setCertNo(_certNo);
            code.setCreated(new Date());
            code.setStatus(InviteCodeStatus.CREATED);
            codeBeans.add(code);
        }

        try {
            inviteCodeService.add(codeBeans);
        } catch (Exception e) {
            return errorJson("保存报名序号失败");
        }

        return dataJson("保存成功");
    }

    @RequestMapping(value = "active", method = RequestMethod.GET)
    public String active(@RequestParam("id") Integer id, @RequestParam(value = "forward", required = false) String forward) {
        return updateStatus(id, InviteCodeStatus.ACTIVED, null);
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@RequestParam("id") Integer id, @RequestParam(value = "forward", required = false) String forward) {
        return updateStatus(id, InviteCodeStatus.DELETED, null);
    }

    protected String updateStatus(int id, int status, String forward) {

        InviteCode code = new InviteCode();
        code.setId(id);
        code.setStatus(status);
        code.setUpdated(new Date());

        try {
            inviteCodeService.update(code);
        } catch (Exception e) {
            logger.error("update status failed. e={}, id={}", e, id);
        }

        if (!StringUtil.isEmpty(forward)) {
            return "redirect:" + forward;
        }

        return "redirect:/invitecode/list.htm";
    }
}
